package com.asynctm.android.common.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.ContactsContract;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.SimpleCursorAdapter;

import com.asynctm.android.R;

/**
 * Utilidades para el tratamiento de objetos propios de Android
 * 
 * @author rockdrigo
 */
public class AndroidUtil {

	/** Tag para el log */
	public static final String LOG_TAG = AndroidUtil.class.getName();

	/** Tipo de dialogo con un solo boton */
	public static final int DIALOG_TYPE_ONE_BUTTON = 0;

	/** Tipo de dialogo con dos botones */
	public static final int DIALOG_TYPE_TWO_BUTTONS = 1;

	/** Tipo de dialogo con tres botones */
	public static final int DIALOG_TYPE_THREE_BUTTONS = 2;

	/**
	 * Muestra un dialogo de mensaje con 1 a tres botones
	 * 
	 * @param context
	 * @param strMessage
	 * @param buttonsOnClickListener
	 */
	public static void showDialog(Context context, int dialogType,
			String message, String positiveButtonLabel,
			String negativeButtonLabel, String neutralButtonLabel,
			DialogInterface.OnClickListener buttonsOnClickListener) {
		AlertDialog dialog = new AlertDialog.Builder(context).create();
		dialog.setMessage(message);
		switch (dialogType) {
		case DIALOG_TYPE_ONE_BUTTON:
			dialog.setButton(DialogInterface.BUTTON_POSITIVE,
					positiveButtonLabel, buttonsOnClickListener);
			break;
		case DIALOG_TYPE_TWO_BUTTONS:
			dialog.setButton(DialogInterface.BUTTON_POSITIVE,
					positiveButtonLabel, buttonsOnClickListener);
			dialog.setButton(DialogInterface.BUTTON_NEGATIVE,
					negativeButtonLabel, buttonsOnClickListener);
			break;
		case DIALOG_TYPE_THREE_BUTTONS:
			dialog.setButton(DialogInterface.BUTTON_POSITIVE,
					positiveButtonLabel, buttonsOnClickListener);
			dialog.setButton(DialogInterface.BUTTON_NEGATIVE,
					negativeButtonLabel, buttonsOnClickListener);
			dialog.setButton(DialogInterface.BUTTON_NEUTRAL,
					neutralButtonLabel, buttonsOnClickListener);
			break;
		default:
			dialog.setButton(DialogInterface.BUTTON_POSITIVE,
					positiveButtonLabel, buttonsOnClickListener);
			break;
		}
		dialog.show();
	}

	/**
	 * Muestra un dialogo de mensaje con un solo boton
	 * 
	 * @param context
	 * @param messageResId
	 * @param okButtonTextResId
	 * @param okButtonOnClickListener
	 */
	public static void showDialog(Context context, int messageResId,
			int okButtonTextResId,
			DialogInterface.OnClickListener okButtonOnClickListener) {
		showDialog(context, DIALOG_TYPE_ONE_BUTTON,
				context.getString(messageResId),
				context.getString(okButtonTextResId), "", "",
				okButtonOnClickListener);
	}

	/**
	 * Muestra un dialogo con una lista de opciones
	 * 
	 * @param context
	 * @param itemsResId
	 * @param titleResId
	 * @param listener
	 */
	public static void showListDialog(Context context, int itemsResId,
			int titleResId, DialogInterface.OnClickListener listener) {
		showListDialog(context,
				context.getResources().getStringArray(itemsResId),
				context.getString(titleResId), listener);
	}

	/**
	 * Muestra un dialogo con una lista de opciones
	 * 
	 * @param context
	 * @param items
	 * @param title
	 * @param listener
	 */
	public static void showListDialog(Context context, String[] items,
			String title, DialogInterface.OnClickListener listener) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(title);
		builder.setItems(items, listener);
		AlertDialog dialog = builder.create();
		dialog.show();
	}

	/**
	 * Muestra un dialogo con una lista de opciones
	 * 
	 * @param context
	 * @param items
	 * @param title
	 * @param listener
	 */
	public static void showListDialog(Context context, List<String> items,
			String title, DialogInterface.OnClickListener listener) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(title);
		String[] arrayItems = new String[items.size()];
		for (int i = 0; i < items.size(); i++) {
			arrayItems[i] = items.get(i);
		}
		builder.setItems(arrayItems, listener);
		AlertDialog dialog = builder.create();
		dialog.show();
	}

	/**
	 * Crea un dialogo personalizado
	 * 
	 * @param ctx
	 * @param title
	 * @param customLayout
	 */
	public static AlertDialog createCustomDialog(String title, View customLayout) {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				customLayout.getContext());
		builder.setView(customLayout);
		AlertDialog alertDialog = builder.create();
		alertDialog.setTitle(title);
		return alertDialog;
	}

	/**
	 * Verifica la conectividad de red
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkReachable(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo == null) {
			return false;
		}
		return (networkInfo.getState() == NetworkInfo.State.CONNECTED);
	}

	/**
	 * 
	 * @param context
	 * @param v
	 */
	public static void hideSoftKeyboard(Context context, View v) {
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
	}

	/**
	 * Devuelve todos los contactos del dispositivo ordenados por nombre
	 * 
	 * @param activity
	 * @return
	 */
	public static Cursor getContacts(Activity activity) {
		String[] projection = new String[] { ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME };
		Cursor contacts = activity.managedQuery(
				ContactsContract.Contacts.CONTENT_URI, projection, null, null,
				ContactsContract.Contacts.DISPLAY_NAME);
		return contacts;
	}

	/**
	 * Devuelve un adapter que contiene una lista de todos los contactos del
	 * dispositivo ordenados por nombre
	 * 
	 * @param activity
	 * @return
	 */
	public static SimpleCursorAdapter getContactsListAdapter(Context context,
			Cursor contacts, int itemLayoutResId, int lblNameResId) {
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(context,
				itemLayoutResId, contacts,
				new String[] { ContactsContract.Contacts.DISPLAY_NAME },
				new int[] { lblNameResId });
		return adapter;
	}

	/**
	 * Carga la actividad para enviar un email
	 * 
	 * @param context
	 * @param to
	 * @param cc
	 * @param bcc
	 * @param subject
	 * @param text
	 * @param attachments
	 */
	public static void loadEmailApp(Context context, String[] to, String[] cc,
			String[] bcc, String subject, String text, File[] attachments) {
		Intent mailIntent = new Intent();
		mailIntent.setType("message/rfc822");

		// Evaluar cantidad de attachments
		if (attachments == null || attachments.length == 0) {
			mailIntent.setAction(Intent.ACTION_SEND);
		} else if (attachments.length == 1) {
			mailIntent.setAction(Intent.ACTION_SEND);
			mailIntent.putExtra(Intent.EXTRA_STREAM,
					Uri.fromFile(attachments[0]));
		} else if (attachments.length > 1) {
			mailIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
			ArrayList<Uri> files = new ArrayList<Uri>();
			for (File file : attachments) {
				files.add(Uri.fromFile(file));
				mailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,
						files);
			}
		}

		if (to == null || to.length == 0)
			throw new RuntimeException("Empty TO field");
		mailIntent.putExtra(Intent.EXTRA_EMAIL, to);

		if (cc != null && cc.length != 0) {
			mailIntent.putExtra(Intent.EXTRA_CC, cc);
		}

		if (bcc != null && bcc.length != 0) {
			mailIntent.putExtra(Intent.EXTRA_BCC, bcc);
		}

		if (!StringUtil.isBlank(subject)) {
			mailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
		}

		if (!StringUtil.isBlank(text)) {
			mailIntent.putExtra(Intent.EXTRA_TEXT, text);
		}

		try {
			context.startActivity(mailIntent);
		} catch (ActivityNotFoundException e) {
			showDialog(context, R.string.msg_no_email_app,
					R.string.lbl_ok_dialog_button, new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
						}
					});
		}
	}

}
